package managedbean;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.persistence.PersistenceException;

import model.Book;
import model.Category;

import org.apache.log4j.Logger;

import dao.BookDao;

@ManagedBean(name="bookListBean")
@ViewScoped
public class BookListManagedBean implements Serializable {

	public static Logger log = Logger.getLogger(BookListManagedBean.class);
	
	private List<Book> books;
	private Category searchCategory;
	
	@ManagedProperty(value="#{bookDao}")
	private BookDao bookDao;
	
	public BookDao getBookDao() {
		return bookDao;
	}
	
	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}

	public Category getSearchCategory() {
		return searchCategory;
	}
	
	public void setsearchCategory(Category category) {
		this.searchCategory = category;
	}	
	
	public List<Book> getBooks() {
		return books;	
	}

	public void setBooks(List<Book> books) {
		this.books = books;
	}

	public void initBookList() {
		setBooks(getBookDao().getBooks());
	}
	
	@PostConstruct
	public void initEditBookList() {
		setBooks(getBookDao().getBooks());
	}
	
	public String searchBooksByCategory(Category aCategory) {
		String result = null;
		searchCategory = aCategory;
		try {
			setBooks(getBookDao().getBooksByCategory(aCategory));
			result = "books";
		} catch (PersistenceException e) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erreur lors de l'accès aux données", e.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, message);
		}
		return result;
	}
	
}
